<template>
  <BasicDrawer
    v-bind="$attrs"
    :okAuth="'inspectionmanag:inTaskCollection:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  destroyOnClose={true}
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <div class="fireVeIm">
      <div v-for="(src, index) in videoSrcList" :key="index" class="fireVideo">
        <span>
          巡检视频 {{ index + 1 }}：
        </span>
        <video
          width="100%"
          height="100%"
          :src="src"
          controls
          autoplay
          muted
          @loadeddata="onVideoLoaded"
          @error="onVideoError"
          type="video/mp4"
        >
        </video>
      </div>
    </div>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup name="ViewsInspectionmanagInTaskCollectionForm">
import { ref, unref, computed } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { InTaskCollection, inTaskCollectionSave, inTaskCollectionListData } from '/@/api/inspectionmanag/inTaskCollection';

const emit = defineEmits(['success', 'register']);

const { t } = useI18n('inspectionmanag.inTaskCollection');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);
const record = ref<InTaskCollection>({} as InTaskCollection);
const videoSrc = ref('');
const videoSrcList = computed(() => {
  return videoSrc.value.split(',').map((src) => src.trim());
});

const getTitle = computed(() => ({
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: record.value.isNewRecord? t('巡检视频') : t('巡检视频'),
}));

const inputFormSchemas: FormSchema[] = [];

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  schemas: inputFormSchemas,
  baseColProps: { md: 24, lg: 12 },
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ loading: true });
  await resetFields();
  
  // 检查 data 中是否包含 tid
  if (!data ||!data.id) {
    console.error('未传入有效的 id');
    setDrawerProps({ loading: false });
    return;
  }

  const { id } = data;
  try {
    const res = await inTaskCollectionListData({ id });
    // 检查接口返回数据格式
    if (!res ||!res.list || res.list.length === 0) {
      console.error('接口返回数据格式错误，未找到有效的数据');
      setDrawerProps({ loading: false });
      return;
    }

    record.value = res.list[0] as InTaskCollection;
    record.value.__t = new Date().getTime();
    // 假设视频地址字段是 videoUrl
    videoSrc.value = record.value.videoUrl || '';
    console.log('videoSrc', videoSrc.value);
    setFieldsValue(record.value);
  } catch (error) {
    console.error('调用 inTaskCollectionListData 接口出错:', error);
  } finally {
    setDrawerProps({ loading: false });
  }
});

const onVideoLoaded = () => {
  console.log('视频加载成功');
};

const onVideoError = () => {
  console.log('视频加载失败');
};

async function handleSubmit() {
  try {
    const data = await validate();
    setDrawerProps({ confirmLoading: true });
    const params: any = {
      isNewRecord: record.value.isNewRecord,
      tid: record.value.id, // 假设使用 id 作为唯一标识
    };
    const res = await inTaskCollectionSave(params, data);
    showMessage(res.message);
    setTimeout(closeDrawer);
    emit('success', data);
  } catch (error: any) {
    if (error && error.errorFields) {
      showMessage(error.message || t('common.validateError'));
    }
    console.log('error', error);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

<style scoped lang="less">
.fireVeIm{
  width:100%;
  height:300px;
  .fireVideo{
    height: 500px;
  }
}
</style>